const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const util = require('./util');
const { addListener } = require('cluster');

/**
 * 从某个HTML文件读取能被Webview加载的HTML内容
 * @param {*} context 上下文
 * @param {*} templatePath 相对于插件根目录的html文件相对路径
 */
function getWebViewContent (context, templatePath) {
  const resourcePath = util.getExtensionFileAbsolutePath(context, templatePath);
  const dirPath = path.dirname(resourcePath);
  let html = fs.readFileSync(resourcePath, 'utf-8');
  // vscode不支持直接加载本地资源，需要替换成其专有路径格式，这里只是简单的将样式和JS的路径替换
  html = html.replace(/(<link.+?href="|<script.+?src="|<img.+?src=")(.+?)"/g, (m, $1, $2) => {
    return $1 + vscode.Uri.file(path.resolve(dirPath, $2)).with({ scheme: 'vscode-resource' }).toString() + '"';
  });
  return html;
}

/**
 * 执行回调函数
 * @param {*} panel 
 * @param {*} message 
 * @param {*} resp 
 */
function invokeCallback (panel, message, resp) {
  // console.log('回调消息：', resp);
  // 错误码在400-600之间的，默认弹出错误提示
  if (typeof resp === 'object' && resp.code && resp.code >= 400 && resp.code < 600) {
    util.showError(resp.message || '发生未知错误！');
  }
  panel.webview.postMessage({ cmd: 'vscodeCallback', cbid: message.cbid, data: resp });
}

/**
 * 存放所有消息回调函数，根据 message.cmd 来决定调用哪个方法
 */
const messageHandler = {
  //读取package.json配置
  async readPackageJson (global, message) {
    const folderUri = vscode.workspace.workspaceFolders[0].uri;
    const fileUri = folderUri.with({ path: path.posix.join(folderUri.path, 'package.json') });
    try {
      const stat = await vscode.workspace.fs.stat(fileUri);
      const readData = await vscode.workspace.fs.readFile(fileUri);
      const readStr = Buffer.from(readData).toString('utf8');
      const projectName = JSON.parse(readStr)['name'];
      invokeCallback(global.panel, message, { code: 0, text: projectName },);
    } catch (error) {
      util.showInfo("package.json不存在");

    }

  },
  //初始化项目时判断是否存在配置文件  如果没有就创建 如果有就忽略
  async initJsonConfig (global, message) {
    const writeStr = JSON.stringify({ "name": "凹凸曼", "environment": "dev" });
    const writeData = Buffer.from(writeStr, 'utf8');
    const folderUri = vscode.workspace.workspaceFolders[0].uri;
    const fileUri = folderUri.with({ path: path.posix.join(folderUri.path, 'sky.config.json') });
    try {
      const stat = await vscode.workspace.fs.stat(fileUri);
      util.showInfo("sky.config.jsony已存在");
    } catch (error) {
      util.showInfo("sky.config.json不存在");
      await vscode.workspace.fs.writeFile(fileUri, writeData);
    } finally {
      const readData = await vscode.workspace.fs.readFile(fileUri);
      const readStr = Buffer.from(readData).toString('utf8');
      const readObject = JSON.parse(readStr);
      invokeCallback(global.panel, message, { code: 0, text: readObject },);
    }

  },
  //启动项目
  runProject (global) {
    util.runProject();
    util.showInfo("项目启动成功");
  },
  // 弹出提示
  alert (global, message) {
    util.showInfo(message.info);
  },
  // 显示错误提示
  error (global, message) {
    util.showError(message.info);
  },
  openUrlInBrowser (global, message) {
    util.openUrlInBrowser(message.url);
    invokeCallback(global.panel, message, { code: 0, text: '成功' });
  },
  openFileInVscode (global, message) {
    util.openFileInVscode(`${global.projectPath}/${message.path}`, message.text);
    invokeCallback(global.panel, message, { code: 0, text: '成功' });
  },
  openFileInSkyConfig (global, message) {

    util.openFileInSkyConfig(`${global.projectPath}/${message.path}`, message.text, message.option);
    invokeCallback(global.panel, message, { code: 0, text: '成功' });

  }
};

module.exports = function (context) {

  // 注册命令，可以给命令配置快捷键或者右键菜单
  // 回调函数参数uri：当通过资源管理器右键执行命令时会自动把所选资源URI带过来，当通过编辑器中菜单执行命令时，会将当前打开的文档URI传过来

  context.subscriptions.push(vscode.commands.registerCommand('extension.demo.openWebview', function (uri) {

    // 工程目录一定要提前获取，因为创建了webview之后activeTextEditor会不准确
    const projectPath = util.getProjectPath(uri);
    if (!projectPath) { return; }
    // 创建webview
    const panel = vscode.window.createWebviewPanel(
      'testWebview', // viewType
      "天好前端项目配置中心", // 视图标题
      vscode.ViewColumn.One, // 显示在编辑器的哪个部位
      {
        enableScripts: true, // 启用JS，默认禁用
        retainContextWhenHidden: true, // webview被隐藏时保持状态，避免被重置
      }
    );

    panel.webview.html = getWebViewContent(context, '/view/test-webview.html');

    let global = { panel, projectPath };
    panel.webview.onDidReceiveMessage(message => {
      if (messageHandler[message.cmd]) {
        messageHandler[message.cmd](global, message);
      } else {
        util.showError(`未找到名为 ${message.cmd} 回调方法!`);
      }
    }, undefined, context.subscriptions);
  }));

};
